package com.zj.user.controller;


import com.zj.user.component.UserRoleAuthentication;
import com.zj.user.domain.User;
import com.zj.user.enums.RoleEnum;
import com.zj.user.enums.UserEnum;
import com.zj.user.service.UserService;
import com.zj.user.utils.*;
import com.zj.user.vo.ResultVo;
import com.zj.user.vo.UserAndApiKeyVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * @Auther: zj
 * @Date: 2018/11/22 16:32
 * @Description: 用户鉴权中心
 */
@RestController
@RequestMapping("/login")
public class AuthController {

    @Autowired
    UserService userService;

    @Autowired
    JwtTokenUtil jwtTokenUtil;

    @Autowired
    UserRoleAuthentication userRoleAuthentication;

    //用户登录（普通用户）
    @PostMapping("/customer")
    public ResultVo customer(@RequestParam("username") String username,
                             @RequestParam("password") String password) {
        User user = userService.findOneUserByUsername( username );
        if (user == null) {
            return ResultVoUtil.error( UserEnum.USERLOGINFailTURE);
        }

        if (user.getHasFreeze()==1) {
            return ResultVoUtil.error( UserEnum.USER_HAFREEZE.getMessage() );
        }

        if (!Objects.equals( RoleEnum.User.getMessage(), user.getRole() )) {//权限校验
            return ResultVoUtil.error( UserEnum.USERROLEERROR);
        }
        if(!Objects.equals( user.getPassword(), MD5Util.encode( password ) )) {
            return ResultVoUtil.error( UserEnum.USERPASSWORDERROR );
        }
        //用jwt生成token
        String token = jwtTokenUtil.generateToken( user );

        return ResultVoUtil.success(token);
    }

    //管理员登录（管理员）
    @PostMapping("/admin")
    public ResultVo admin(@RequestParam("username") String username,
                             @RequestParam("password") String password) {
        User user = userService.findOneUserByUsername( username );
        if (user == null) {
            return ResultVoUtil.error( UserEnum.USERLOGINFailTURE);
        }
        if (!Objects.equals( RoleEnum.Admin.getMessage(), user.getRole() )) {//权限校验
            return ResultVoUtil.error( UserEnum.USERROLEERROR);
        }
        if(!Objects.equals( user.getPassword(), MD5Util.encode( password ) )) {
            return ResultVoUtil.error( UserEnum.USERPASSWORDERROR );
        }
        //用jwt生成token
        String token = jwtTokenUtil.generateToken( user );

        return ResultVoUtil.success(token);
    }

    /**
     * 列出当前用户api-key的信息
     * @param request
     * @return
     */
    @GetMapping("/getApiKeyInfo")
    public ResultVo getApiKeyInfo(HttpServletRequest request) {
        String username = userRoleAuthentication.getUsernameAndAutenticateUserRoleFromRequest( request,RoleEnum.User.getMessage());
        if (Objects.equals( username, "false" )) {
            return ResultVoUtil.error( UserEnum.USERROLEERROR );
        }
        User user = userService.findOneUserByUsername( username );
        if (user.getApiKey()==null) {
            return ResultVoUtil.success();
        }
        UserAndApiKeyVo userAndApiKeyVo = new UserAndApiKeyVo(  );
        userAndApiKeyVo.setUsername( username );
        userAndApiKeyVo.setApiKey( user.getApiKey() );

        ArrayList<UserAndApiKeyVo> list = new ArrayList<>(  );
        list.add( userAndApiKeyVo );

        return ResultVoUtil.success(list);
    }

    //为用户生成唯一的api-key,用户权限
    @GetMapping("/getApiKey")
    public ResultVo generateApiKey(HttpServletRequest request) {
        String username = userRoleAuthentication.getUsernameAndAutenticateUserRoleFromRequest( request,RoleEnum.User.getMessage());
        if (Objects.equals( username, "false" )) {
            return ResultVoUtil.error( UserEnum.USERROLEERROR );
        }
        User user = userService.findOneUserByUsername( username );
        if (user.getApiKey()!=null) {
            return ResultVoUtil.error( UserEnum.USERAPIKEYISNOTNULL );
        }
        String apiKey = RandomUtils.uuid();

        user.setApiKey( apiKey );
        userService.UpDate( user );

        return ResultVoUtil.success(apiKey);
    }

    /**
     * 删除用户api-key,用户权限
     * @param request
     * @return
     */
    @GetMapping("/removeApiKey")
    public ResultVo removeApiKey(HttpServletRequest request) {
        String username = userRoleAuthentication.getUsernameAndAutenticateUserRoleFromRequest( request,RoleEnum.User.getMessage());
        if (Objects.equals( username, "false" )) {
            return ResultVoUtil.error( UserEnum.USERROLEERROR );
        }
        User user = userService.findOneUserByUsername( username );
        user.setApiKey(null);
        userService.UpDate( user );

        return ResultVoUtil.success();
    }

}
